import { UAParser } from "ua-parser-js";
import { PrismaClient } from "@prisma/client";
import IP2Region from "ip2region";
import { Injectable } from "@nestjs/common";
const prisma = new PrismaClient();

@Injectable()
export class PageViewService {
  static pageViewClearTimerID = undefined;
  pageViewClearInterval: number = 1000 * 60 * 60 * 12; // 12小时
  constructor() {
    if (!PageViewService.pageViewClearTimerID) {
      PageViewService.pageViewClearTimerID = setTimeout(() => {
        this.clearPageView();
      }, this.pageViewClearInterval);
    }
  }

  // 清空浏览记录
  async clearPageView() {
    const count = await prisma.page_view.count();
    // 10 万条删除
    if (count >= 100000) {
      await prisma.page_view.deleteMany();
    }
  }

  // 创建浏览记录
  async createPageView(request) {
    // 不是访问页面
    if (!request.url.includes(".html") || request.url.includes("/api/")) {
      return;
    }

    const ip =
      request.headers["x-real-ip"] ||
      request.headers["x-forwarded-for"] ||
      request.ip ||
      request.socket?.remoteAddress ||
      undefined;
    if (!ip) {
      return;
    }
    const ipQuery = new IP2Region();
    const ipRegion = ipQuery.search(ip);
    // console.log(ipRegion);
    const area = `${ipRegion.country || ""}${ipRegion.province || ""}${ipRegion.city === "内网IP" ? "" : ipRegion.city}`;

    const userAgent = request.headers["user-agent"] || "";
    const platformVersion = request.headers["sec-ch-ua-platform-version"];
    const parser = new UAParser(userAgent);
    const uaResult = parser.getResult();

    let osVersion = uaResult.os.version;
    // Windows 11
    if (
      uaResult.os.name === "Windows" &&
      platformVersion &&
      parseInt(platformVersion.substring(1)) >= 13
    ) {
      osVersion = "11";
    }

    const os = `${uaResult.os.name || "未知"} ${osVersion || ""}`;
    const browser = `${uaResult.browser.name || "未知"} ${uaResult.browser.version || ""}`;

    const createView = async () => {
      await prisma.page_view.create({
        data: {
          path: request.url,
          ip,
          area,
          os,
          browser,
        },
      });
    };
    await prisma.page_view
      .findMany({
        select: {
          time: true,
        },
        where: {
          path: request.url,
          ip,
        },
        orderBy: {
          time: "desc",
        },
        take: 1,
      })
      .then(async (result) => {
        if (!result || result.length === 0 || !result[0]) {
          await createView();
          return;
        }
        const view = result[0];
        // console.log(view);
        const time = view.time;
        const elapseMS = new Date().getTime() - time.getTime();
        const elapseMinute = elapseMS / 1000 / 60;
        // console.log(elapseMinute);

        // 每分钟记一次，不到一分钟，不记
        if (elapseMinute < 1) {
          return;
        }
        await createView();
      });
  }
}
